export default function createWS(
  url,
  cb,
  binaryType = null,
  onError = null,
  onOpen = null,
  onClose = null,
) {
  const ws = new WebSocket(url);
  if (binaryType) {
    ws.binaryType = binaryType;
  }
  ws.onopen = function () {
    console.log(`${url} connected`);
    onOpen && onOpen();
  };
  ws.onmessage = function (e) {
    //连接建立才接收数据回调
    if (ws.readyState == 1) {
      cb(e.data);
    }
  };
  // 需要服务端响应了才会触发，因此服务器端延时会造成客户端关闭延时
  ws.onclose = function () {
    console.log(`${url} closed`);
    onClose && onClose();
  };
  ws.onerror = (e) => {
    onError && onError(e);
  };
  return ws;
}
